<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>朋友圈</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="../static/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 配置Tailwind自定义颜色和字体 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#64748B',
                        light: '#F1F5F9',
                        dark: '#1E293B',
                        purple: {
                            DEFAULT: '#6a11cb',
                            dark: '#5a0dc8'
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer base {
            body {
                width: 100%;
                margin: 0;
                padding: 0;
            }
        }

        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .container-full {
                width: 100%;
                max-width: 100%;
                padding-left: 1rem;
                padding-right: 1rem;
            }
            @screen md {
                .container-full {
                    padding-left: 2rem;
                    padding-right: 2rem;
                }
            }
            @screen lg {
                .container-full {
                    padding-left: 4rem;
                    padding-right: 4rem;
                }
            }
        }

        /* 按钮样式 */
        .btn-custom {
            background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        .btn-custom:hover {
            background: linear-gradient(45deg, #5a0dc8 0%, #1a69e0 100%);
            transform: translateY(-2px);
        }
        .btn-custom:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .btn-icon {
            color: #6a11cb;
            background: transparent;
            border: none;
            padding: 8px 12px;
            cursor: pointer;
            transition: color 0.3s;
        }
        .btn-icon:hover {
            color: #A859FF;
        }
        .btn-icon:disabled {
            color: #ccc;
            cursor: not-allowed;
        }

        /* 加载动画 */
        .loading-indicator {
            text-align: center;
            padding: 1rem;
            color: #64748B;
        }

        /* 评论区样式 */
        .comments-section {
            margin-top: 12px;
            padding-top: 12px;
            border-top: 1px solid #eee;
        }

        .comments-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .comments-title {
            font-size: 14px;
            font-weight: bold;
            color: #333;
        }

        .comment-input {
            display: flex;
            margin-bottom: 15px;
        }

        .comment-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #eee;
            margin-right: 8px;
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 14px;
        }

        .comment-textarea {
            flex-grow: 1;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 8px 12px;
            resize: none;
            font-family: inherit;
            font-size: 13px;
            height: 70px;
        }

        .comment-submit {
            background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
            margin-left: 8px;
            align-self: flex-end;
        }

        .comment-first-level {
            margin-bottom: 15px;
        }

        .comment-item {
            display: flex;
            margin-bottom: 12px;
            padding-bottom: 12px;
            border-bottom: 1px solid #f0f0f0;
        }

        .comment-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }

        .comment-author {
            font-weight: bold;
            font-size: 13px;
            margin-bottom: 3px;
        }

        .comment-time {
            font-size: 11px;
            color: #999;
            margin-bottom: 3px;
        }

        .comment-content {
            font-size: 13px;
            margin-bottom: 5px;
        }

        .comment-actions {
            display: flex;
            gap: 12px;
            font-size: 11px;
        }

        .comment-action {
            color: #666;
            cursor: pointer;
            display: flex;
            align-items: center;
        }

        .comment-action i {
            margin-right: 2px;
            font-size: 11px;
        }

        .comment-action:hover {
            color: #6a11cb;
        }

        /* 二级子评论样式 */
        .comment-second-level {
            margin-left: 20px;
            padding-top: 8px;
        }

        /* 点赞状态样式 */
        .action-btn.liked i,
        .comment-action.liked i {
            color: #6a11cb;
        }

        /* 评论区点赞 hover 效果 */
        .comment-action.like:hover i {
            color: #6a11cb;
        }
        .comment-action.like.liked i {
            color: #6a11cb;
        }

        /* 图片预览容器 */
        .image-preview {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin: 8px 0;
        }
        .image-preview-item {
            width: 80px;
            height: 80px;
            border-radius: 4px;
            overflow: hidden;
            position: relative;
        }
        .image-preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .image-preview-item .remove-img {
            position: absolute;
            top: -8px;
            right: -8px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #ff4d4f;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 12px;
        }

        /* 店铺选择样式 */
        .shop-select-container {
            margin: 8px 0;
        }
        .shop-input-wrapper {
            position: relative;
            width: 100%;
        }
        .shop-input {
            width: 100%;
            padding: 8px 12px 8px 36px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 13px;
        }
        .shop-input-icon {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
        }
        .shop-suggest-list {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            z-index: 100;
            background: white;
            border: 1px solid #ddd;
            border-top: none;
            border-radius: 0 0 6px 6px;
            max-height: 200px;
            overflow-y: auto;
        }
        .shop-suggest-item {
            padding: 8px 12px;
            cursor: pointer;
            font-size: 13px;
        }
        .shop-suggest-item:hover {
            background: #f5f5f5;
        }
        .shop-select-status {
            margin-top: 4px;
            font-size: 12px;
        }
        .status-warning {
            color: #ff9800;
        }
        .status-success {
            color: #4caf50;
        }

        /* 朋友圈分享弹窗样式 */
        .share-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        .share-content {
            background-color: white;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        }
        .share-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .share-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
        .close-modal {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #999;
        }
        .share-link-section {
            margin-bottom: 10px;
        }
        .link-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }
        .link-container {
            display: flex;
            gap: 8px;
            align-items: center;
        }
        #shopLinkInput {
            flex-grow: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 13px;
            color: #333;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .copy-btn {
            background-color: #6a11cb;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
            transition: background-color 0.3s;
        }
        .copy-btn:hover {
            background-color: #5a0dc8;
        }
    </style>
</head>
<body class="font-inter bg-gray-50 text-dark w-full">

<div class="container-full py-4 pb-24">
    <!-- 发布新动态 -->
    <div class="bg-white rounded-xl shadow-sm p-5 mb-6">
        <div class="flex gap-4">
            <div class="w-14 h-14 rounded-full bg-gradient-to-r from-purple-400 to-pink-500 flex items-center justify-center text-white font-bold text-lg" id="userAvatar">
                我
            </div>
            <div class="flex-1">
                <!-- 动态内容输入框 -->
                <textarea
                        class="w-full border border-gray-200 rounded-lg p-4 focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all resize-none"
                        rows="2"
                        placeholder="分享新鲜事..." id="momentContent"></textarea>

                <!-- 新增：店铺选择模块（强制流程） -->
                <div class="shop-select-container">
                    <div class="shop-input-wrapper">
                        <i class="fa fa-map-marker shop-input-icon"></i>
                        <input
                                type="text"
                                class="shop-input"
                                id="shopNameInput"
                                placeholder="请输入店铺名（必填）"
                        >
                        <!-- 店铺模糊查询结果列表 -->
                        <div class="shop-suggest-list hidden" id="shopSuggestList"></div>
                    </div>
                    <!-- 选择状态提示 -->
                    <div class="shop-select-status status-warning" id="shopSelectStatus">
                        <i class="fa fa-exclamation-circle"></i> 请先选择打卡店铺
                    </div>
                    <!-- 隐藏域存储选中的shop_id和shop_name -->
                    <input type="hidden" id="selectedShopId" value="">
                    <input type="hidden" id="selectedShopName" value="">
                </div>

                <!-- 图片预览容器 -->
                <div class="image-preview" id="imagePreviewContainer"></div>

                <!-- 功能按钮区（默认禁用图片上传和发布） -->
                <div class="flex justify-between mt-4">
                    <div class="flex gap-2">
                        <button class="btn-icon flex items-center" id="uploadImageBtn" disabled>
                            <i class="fa fa-image mr-2"></i> 图片
                        </button>
                        <!-- 隐藏的文件输入框 -->
                        <input type="file" id="imageUploadInput" multiple accept="image/*" style="display: none;" disabled>

<!--                        <button class="btn-icon flex items-center" id="emojiBtn" disabled>-->
<!--                            <i class="fa fa-smile-o mr-2"></i> 表情-->
<!--                        </button>-->
                        <button class="btn-custom" id="checkinBtn">
                            我的打卡记录
                        </button>
                    </div>
                    <button class="btn-custom" id="publishBtn" disabled>
                        发布
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 动态列表（动态渲染容器） -->
    <div class="space-y-3" id="momentsList"> <!-- 缩小动态间距 -->
        <!-- 初始加载提示 -->
        <div class="text-center py-6"> <!-- 缩小加载提示高度 -->
            <i class="fa fa-spinner fa-spin text-primary text-xl"></i>
            <p class="mt-2 text-gray-500">加载中...</p>
        </div>
    </div>

    <!-- 底部加载提示（默认隐藏） -->
    <div class="loading-indicator hidden" id="loadingMore">
        <i class="fa fa-spinner fa-spin"></i>
        <span class="ml-2">加载更多内容...</span>
    </div>

    <!-- 无更多数据提示（默认隐藏） -->
    <div class="text-center py-3 text-gray-500 hidden" id="noMoreData"> <!-- 缩小提示高度 -->
        已显示全部内容
    </div>
</div>

<!-- 大图预览模态框 -->
<div id="imagePreviewModal" class="fixed inset-0 bg-black/80 flex items-center justify-center z-50 hidden">
    <button id="closeModal" class="absolute top-4 right-4 text-white text-2xl">×</button>
    <div class="flex flex-col items-center">
        <img id="modalImage" src="" alt="大图预览" class="max-w-full max-h-[80vh]" style="transform: scale(1); transition: transform 0.3s;">
    </div>
</div>

<!-- 分享弹窗（朋友圈专用，仅复制链接） -->
<div class="share-modal" id="shareModal">
    <div class="share-content">
        <div class="share-header">
            <h3 class="share-title">分享店铺链接</h3>
            <button class="close-modal" onclick="closeShareModal()">&times;</button>
        </div>
        <!-- 链接复制区域 -->
        <div class="share-link-section">
            <div class="link-label">店铺链接</div>
            <div class="link-container">
                <input type="text" id="shopLinkInput" value="" readonly>
                <button class="copy-btn" onclick="copyShopLink()">复制链接</button>
            </div>
        </div>
    </div>
</div>


<script src="../static/js/jquery.js"></script>
<script src="../static/js/jquery.cookie.js"></script>

<script>
    $(document).ready(function() {
        // 核心变量
        const userName = $.cookie("username");
        let userId = null;
        let pageSize = 10;
        let isLoading = false;
        let hasMoreData = true;
        let selectedImages = []; // 存储选中的图片文件和预览地址
        let isShopSelected = false; // 店铺是否已选择（控制按钮启用状态）

        // 存储已点赞的动态ID和评论ID
        let likedMomentIds = new Set();
        let likedCommentIds = new Set();

        // 点击预览图片相关变量
        let scale = 1; // 初始缩放比例
        const scaleStep = 0.2; // 每次缩放的步长
        const maxScale = 3; // 最大缩放比例
        const minScale = 0.5; // 最小缩放比例

        // 初始化事件监听
        initEventListeners();
        // 绑定滚动事件
        bindScrollEvent();

        // 初始化加载
        if (userName) {
            getUserIdByName(userName, function(id) {
                userId = id;
                if (userId) {
                    showUserInfoByUserId(userId);
                    // 获取用户点赞记录
                    getUserLikedMoments();
                }
                // 首次加载10条
                loadMoreData();
            });
        } else {
            $('#momentsList').html('<div class="text-center py-6">请先登录</div>');
        }

        // 初始化事件监听
        function initEventListeners() {

            // -------------------------- 朋友圈分享功能（仅复制链接） --------------------------
// 1. 打开分享弹窗（接收动态的店铺ID）
            window.openShareModal = function(shopId) {
                // 生成店铺详情页链接（和个人打卡页面保持一致）
                const shopLink = `http://localhost:8080/homepage/goToDetail?id=${shopId}`;
                document.getElementById('shopLinkInput').value = shopLink;
                // 显示弹窗
                document.getElementById('shareModal').style.display = 'flex';
            };

// 2. 关闭分享弹窗
            window.closeShareModal = function() {
                document.getElementById('shareModal').style.display = 'none';
            };

// 3. 复制链接并提示
            window.copyShopLink = function() {
                const linkInput = document.getElementById('shopLinkInput');
                linkInput.select(); // 选中链接
                document.execCommand('copy'); // 执行复制
                // 复制成功提示（2秒后恢复）
                const copyBtn = document.querySelector('.copy-btn');
                const originalText = copyBtn.textContent;
                copyBtn.textContent = '已复制!';
                setTimeout(() => {
                    copyBtn.textContent = originalText;
                }, 2000);
            };

// 4. 绑定分享按钮点击事件（触发弹窗）
            $('#momentsList').on('click', '.share-btn', function() {
                // 获取当前动态的店铺ID
                const shopId = $(this).closest('.moment-item').find('.fa-map-marker').parent().data('shop-id');
                // 打开分享弹窗
                openShareModal(shopId);
            });

            //------------------------点击图片进行大图预览----------------------
            // 放大图片
            $('#zoomIn').on('click', function() {
                if (scale < maxScale) {
                    scale += scaleStep;
                    $('#modalImage').css('transform', `scale(${scale})`);
                }
            });

            // 缩小图片
            $('#zoomOut').on('click', function() {
                if (scale > minScale) {
                    scale -= scaleStep;
                    $('#modalImage').css('transform', `scale(${scale})`);
                }
            });

            // 鼠标滚轮缩放（可选，增强交互）
            $('#modalImage').on('wheel', function(e) {
                e.preventDefault();
                if (e.originalEvent.deltaY < 0) {
                    // 滚轮向上 → 放大
                    if (scale < maxScale) {
                        scale += scaleStep;
                        $(this).css('transform', `scale(${scale})`);
                    }
                } else {
                    // 滚轮向下 → 缩小
                    if (scale > minScale) {
                        scale -= scaleStep;
                        $(this).css('transform', `scale(${scale})`);
                    }
                }
            });

            // 关闭模态框时重置缩放比例
            $('#closeModal, #imagePreviewModal').on('click', function() {
                scale = 1;
                $('#modalImage').css('transform', 'scale(1)');
                $('#imagePreviewModal').addClass('hidden');
            });

            // -------------------------- 新增：店铺选择相关事件 --------------------------
            // 店铺输入框模糊查询
            $('#shopNameInput').on('input', function() {
                const shopName = $(this).val().trim();
                const suggestList = $('#shopSuggestList');

                if (shopName.length < 1) { // 输入1个字符就触发查询
                    suggestList.empty().addClass('hidden');
                    return;
                }

                // 调用后端店铺模糊查询接口
                $.ajax({
                    url: "/Moments/fuzzyQueryShop", // 后端店铺查询接口
                    type: "post",
                    dataType: "json",
                    data: { shopName: shopName },
                    success: function(res) {
                        // console.log("查询出的店铺：",res)
                        if (res.code === 200 && res.data && res.data.length > 0) {
                            let listHtml = '';
                            res.data.forEach(shop => {
                                listHtml += `<div class="shop-suggest-item" data-shop-id="${shop.id}" data-shop-name="${shop.name}">${shop.name}</div>`;
                            });
                            suggestList.html(listHtml).removeClass('hidden');
                        } else {
                            suggestList.html('<div class="shop-suggest-item text-gray-500">未找到匹配店铺</div>').removeClass('hidden');
                        }
                    },
                    error: function() {
                        suggestList.html('<div class="shop-suggest-item text-red-500">查询失败，请重试</div>').removeClass('hidden');
                    }
                });
            });

            // 选择店铺
            $('#shopSuggestList').on('click', '.shop-suggest-item', function() {
                const shopId = $(this).data('shop-id');
                const shopName = $(this).data('shop-name');
                $('#selectedShopId').val(shopId);
                $('#selectedShopName').val(shopName);
                // 将店铺名赋值给输入框
                $('#shopNameInput').val(shopName);
                $('#shopSelectStatus')
                    .removeClass('status-warning')
                    .addClass('status-success')
                    .html(`<i class="fa fa-check-circle"></i> 已选择：${shopName}`);
                $('#shopSuggestList').addClass('hidden');
                // 启用图片上传和发布按钮
                isShopSelected = true;
                $('#uploadImageBtn, #imageUploadInput, #emojiBtn, #publishBtn').prop('disabled', false);
            });

            // -------------------------- 原有事件保持不变 --------------------------
            // 图片上传按钮交互
            $('#uploadImageBtn').on('click', function() {
                if (!isShopSelected) {
                    alert('请先选择打卡店铺');
                    return;
                }
                $('#imageUploadInput').click(); // 触发文件输入框的点击
            });

            // 图片选择变化监听（预览+存储）
            $('#imageUploadInput').on('change', function(e) {
                const files = e.target.files;
                if (files.length === 0) return;

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    const reader = new FileReader();
                    reader.onload = function(event) {
                        // 存储图片信息（文件+预览地址）
                        selectedImages.push({
                            file: file,
                            previewUrl: event.target.result
                        });
                        // 渲染预览
                        renderImagePreview();
                    };
                    reader.readAsDataURL(file);
                }
            });

            // 移除预览图片
            $('#imagePreviewContainer').on('click', '.remove-img', function() {
                const index = $(this).closest('.image-preview-item').data('index');
                selectedImages.splice(index, 1);
                renderImagePreview();
            });

            window.goToDetail = function(id) {
                console.log(id);
                window.location.href = "/homepage/goToDetail?id=" + id;
            };

            // 点赞按钮交互
            $('#momentsList').on('click', '.like-btn', function() {
                const momentId = parseInt($(this).closest('.moment-item').attr('id').replace('moment_', ''));
                toggleMomentLike(momentId);
            });

            //评论按钮点击事件，用于展开评论区
            $('#momentsList').on('click', '.comment-btn', function() {
                const momentId = parseInt($(this).closest('.moment-item').attr('id').replace('moment_', ''));
                toggleComments(momentId);
            });

            // 1. 一级评论点赞（委托给一级评论列表容器）
            $('#momentsList').on('click', '.comment-first-level .comment-action.like.parent-like-btn', function() {
                const commentId = parseInt($(this).closest('.comment-item').attr('id').replace('comment_', ''));
                const momentId = parseInt($(this).closest('.moment-item').attr('id').replace('moment_', ''));
                toggleCommentLike(momentId, commentId);
            });

            // 2. 二级子评论点赞（委托给子评论容器）
            $('#momentsList').on('click', '.comment-second-level .comment-action.like.child-like-btn', function() {
                const commentId = parseInt($(this).closest('.comment-item').attr('id').replace('comment_', ''));
                const momentId = parseInt($(this).closest('.moment-item').attr('id').replace('moment_', ''));
                toggleCommentLike(momentId, commentId);
            });

            // 分享按钮交互
            $('#momentsList').on('click', '.share-btn', function() {
                const momentId = parseInt($(this).closest('.moment-item').attr('id').replace('moment_', ''));
                // alert(`当前动态 ${momentId}`);
            });

            // 回复评论交互
            $('#momentsList').on('click', '.comment-action.reply', function() {
                const $commentItem = $(this).closest('.comment-item'); // 找到当前评论项
                const commentId = parseInt($commentItem.attr('id').replace('comment_', ''));
                const momentId = parseInt($(this).closest('.moment-item').attr('id').replace('moment_', ''));
                const targetUser = $commentItem.find('.comment-author').text(); // 获取评论作者名
                const isChild = $(this).data('is-child'); // 从data属性获取是否为子评论

                // 调用回复函数，传递层级信息
                replyToComment(momentId, commentId, targetUser, isChild);
            });

            // 查看回复交互
            $('#momentsList').on('click', '.comment-action.view-replies', function() {
                const commentId = parseInt($(this).closest('.comment-item').attr('id').replace('comment_', ''));
                const momentId = parseInt($(this).closest('.moment-item').attr('id').replace('moment_', ''));
                toggleChildComments(momentId, commentId);
            });

            // 提交评论
            $('#momentsList').on('click', '.comment-submit', function() {
                const momentId = parseInt($(this).closest('.moment-item').attr('id').replace('moment_', ''));
                submitComment(momentId);
            });

            // 我的打卡记录按钮
            $('#checkinBtn').on('click', function() {
                // alert('切换到我的打卡记录视图');
                window.location.href = "/checkings";
            });

            // 发布按钮
            $('#publishBtn').on('click', function() {
                if (selectedImages.length > 0) {
                    // 有图片，先上传图片再发布动态
                    uploadImages().then((imageUrls) => {
                        publishMoment(imageUrls);
                    }).catch((err) => {
                        alert('图片上传失败，请重试');
                    });
                } else {
                    // 无图片，直接发布动态
                    publishMoment([]);
                }
            });

            // 图片预览
            $('#momentsList').on('click', '.group', handleImagePreview);
        }

        // 渲染图片预览
        function renderImagePreview() {
            const container = $('#imagePreviewContainer');
            container.empty();
            selectedImages.forEach((img, index) => {
                container.append(`
                    <div class="image-preview-item" data-index="${index}">
                        <img src="${img.previewUrl}" alt="预览图">
                        <div class="remove-img">×</div>
                    </div>
                `);
            });
        }

        // 上传图片到OSS服务器
        function uploadImages() {
            return new Promise((resolve, reject) => {
                if (selectedImages.length === 0) {
                    resolve([]);
                    return;
                }

                const formData = new FormData();
                selectedImages.forEach((img, index) => {
                    formData.append(`files`, img.file, img.file.name);
                });

                $.ajax({
                    url: "/uploadList", // 后端多文件上传接口
                    type: "post",
                    data: formData,
                    processData: false,
                    contentType: false,
                    dataType: "json",
                    success: function(res) {
                        console.log("selectedImages:", selectedImages)
                        console.log("上传的文件：", formData)
                        console.log("上传成功：", res)
                        if (res.code === 200 && res.data) {
                            resolve(res.data); // 返回OSS图片访问URL列表
                        } else {
                            reject(res.message || '图片上传失败');
                        }
                    },
                    error: function() {
                        reject('网络异常，图片上传失败');
                    }
                });
            });
        }

        // 发布动态
        function publishMoment(imageUrls) {
            const context = $('#momentContent').val().trim();
            const shopId = $('#selectedShopId').val();

            if (!shopId) {
                alert('请先选择打卡店铺');
                return;
            }

            if (!context && imageUrls.length === 0) {
                alert('请输入动态内容或选择图片');
                return;
            }

            // 将URL数组转为JSON字符串
            const imgsUrlsStr = imageUrls.length > 0 ? JSON.stringify(imageUrls) : null;

            $.ajax({
                url: "/Moments/publishMoment", // 后端发布动态接口
                type: "post",
                dataType: "json",
                data: {
                    context: context,
                    imgsUrls: imgsUrlsStr,
                    userId: userId,
                    shopId: shopId
                },
                success: function(res) {
                    console.log("context", context)
                    console.log("imgsUrls", imgsUrlsStr)
                    console.log("userId", userId)
                    console.log("shopId", shopId)
                    if (res.code === 200) {
                        alert('发布成功');
                        // 清空输入和预览
                        $('#momentContent').val('');
                        selectedImages = [];
                        renderImagePreview();
                        // 重置店铺选择状态
                        $('#shopNameInput').val('');
                        $('#selectedShopId').val('');
                        $('#selectedShopName').val('');
                        $('#shopSelectStatus')
                            .removeClass('status-success')
                            .addClass('status-warning')
                            .html('<i class="fa fa-exclamation-circle"></i> 请先选择打卡店铺');
                        isShopSelected = false;
                        $('#uploadImageBtn, #imageUploadInput, #emojiBtn, #publishBtn').prop('disabled', true);
                        // 重新加载动态列表
                        pageSize = 10;
                        hasMoreData = true;
                        loadMoreData();
                    } else {
                        alert('发布失败：' + (res.message || '未知错误'));
                    }
                },
                error: function() {
                    console.log("content", content)
                    console.log("imgsUrls", imgsUrlsStr)
                    console.log("userId", userId)
                    console.log("shopId", shopId)
                    alert('发布失败，请重试');
                }
            });
        }

        // 绑定滚动事件
        function bindScrollEvent() {
            $(window).scroll(function() {
                if (
                    $(window).scrollTop() + $(window).height() >= $(document).height() - 150 &&
                    hasMoreData &&
                    !isLoading
                ) {
                    loadMoreData();
                }
            });
        }

        // 加载更多数据
        function loadMoreData() {
            if (isLoading || !hasMoreData) return;

            isLoading = true;
            $('#loadingMore').removeClass('hidden');

            $.ajax({
                url: "/Moments/showAllCheckinsByPage",
                type: "post",
                dataType: "json",
                data: {
                    pageSize: pageSize
                },
                success: function(res) {
                    console.log("所有用户的朋友圈打卡：", res)
                    $('#loadingMore').addClass('hidden');

                    if (res.code === 200 && res.data && res.data.length > 0) {
                        const momentsList = $('#momentsList');
                        if (pageSize === 10) {
                            momentsList.empty();
                        }

                        res.data.forEach(item => {
                            if (!$('#moment_' + item.id).length) {
                                momentsList.append(renderMomentItem(item));
                            }
                        });

                        hasMoreData = res.data.length >= pageSize;
                        pageSize += 10;

                        // 加载新数据后，同步点赞状态
                        if (userId) {
                            getUserLikedMoments();
                        }
                    } else if (pageSize === 10) {
                        $('#momentsList').html('<div class="text-center py-6">暂无动态</div>');
                        hasMoreData = false;
                    } else {
                        hasMoreData = false;
                        $('#noMoreData').removeClass('hidden');
                    }

                    isLoading = false;
                },
                error: function() {
                    console.log("加载数据失败");
                    $('#loadingMore').addClass('hidden');
                    isLoading = false;
                    const errorHtml = '<div class="text-center py-3 text-red-500" id="loadError">加载失败，请重试</div>';
                    $('#momentsList').append(errorHtml);
                    setTimeout(() => $('#loadError').remove(), 3000);
                }
            });
        }

        // 渲染单条动态
        function renderMomentItem(item) {
            // 处理用户信息
            const userAvatar = item.user?.icon || 'https://via.placeholder.com/100';
            const userName = item.user?.username || '未知用户';
            const isLiked = likedMomentIds.has(item.id);

            // 处理图片(字符串->字符串数组)
            let imgsArray = [];
            if (item.imgsUrls) {
                try {
                    const cleanedImgsUrls = item.imgsUrls.replace(/\\"/g, '"');
                    imgsArray = JSON.parse(cleanedImgsUrls);
                } catch (e) {
                    imgsArray = [item.imgsUrls];
                }
            }

            let imgHtml = '';
            if (imgsArray && imgsArray.length > 0) {
                imgHtml = `<div class="flex space-x-1 mb-2">`;
                imgsArray.forEach(imgUrl => {
                    imgHtml += `
                        <div class="relative rounded-lg overflow-hidden bg-gray-100 group cursor-pointer w-32 h-32">
                            <img src="${imgUrl}" class="w-full h-full object-cover" alt="动态图片">
                            <div class="absolute inset-0 bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                                <i class="fa fa-search-plus text-white text-xl"></i>
                            </div>
                        </div>
                    `;
                });
                imgHtml += `</div>`;
            }

            // 评论区HTML
            const commentsHtml = `
                <div class="comments-section" id="commentsSection-${item.id}" style="display: none;">
                    <div class="comments-header">
                        <div class="comments-title">评论 (${item.reviews || 0})</div>
                    </div>

                    <div class="comment-input">
                        <textarea class="comment-textarea" placeholder="写下你的评论..." id="commentInput-${item.id}"></textarea>
                        <button class="comment-submit">发布</button>
                    </div>

                    <div class="comment-first-level" id="commentsList-${item.id}">
                        <div class="text-center py-3 text-gray-500 text-sm">
                            加载评论中...
                        </div>
                    </div>
                </div>
            `;

            // 拼接完整HTML
            return `
                <div class="bg-white rounded-lg shadow-sm overflow-hidden transition-all duration-300 hover:shadow-md p-3 moment-item" id="moment_${item.id}">
                    <div class="flex gap-2">
                        <div class="w-10 h-10 rounded-full bg-gray-200">
                            <img src="${userAvatar}" class="w-full h-full rounded-full object-cover" alt="${userName}头像">
                        </div>
                        <div class="flex-1 min-w-0">
                            <div class="flex flex-wrap items-center gap-x-1 gap-y-0.5 mb-1">
                                <h3 class="font-semibold text-dark text-sm">${userName}</h3>
                                <time class="text-xs text-gray-400 ml-auto">${formatTime(item.createdAt)}</time>
                            </div>
                            <p class="text-gray-700 text-sm mb-2">${item.context || '无内容'}</p>
                            ${imgHtml}
                            <div class="flex items-center text-xs text-gray-500 mb-2" onclick="goToDetail(${item.shop?.id})" data-shop-id="${item.shop?.id}">
                              <i class="fa fa-map-marker mr-0.5"></i>
                              <span>${item.shop?.name || '未填写位置'}</span>
                            </div>
                            <div class="flex gap-3 text-xs border-t border-gray-100 pt-2">
                                <button class="flex items-center gap-0.5 text-gray-500 hover:text-primary transition-colors like-btn ${isLiked ? 'liked' : ''}">
                                    <i class="fa fa-heart-o"></i>
                                    <span>点赞 (${item.likes || 0})</span>
                                </button>
                                <button class="flex items-center gap-0.5 text-gray-500 hover:text-primary transition-colors comment-btn">
                                    <i class="fa fa-comment-o"></i>
                                    <span>评论 (${item.reviews || 0})</span>
                                </button>
                                <button class="flex items-center gap-0.5 text-gray-500 hover:text-primary transition-colors share-btn ml-auto">
                                    <i class="fa fa-share"></i>
                                    <span>分享店铺</span>
                                </button>
                            </div>
                            ${commentsHtml}
                        </div>
                    </div>
                </div>
            `;
        }

        // 渲染评论列表
        function renderCommentList(comments, momentId, isChildList = false) {
            // 新增isChildList参数，标记当前渲染的是一级评论还是二级子评论
            if (!comments || comments.length === 0) {
                return `
            <div class="text-center py-3 text-gray-500 text-sm">
                ${isChildList ? '暂无回复，快来抢沙发~' : '暂无评论，快来发表第一条评论吧'}
            </div>
        `;
            }

            let html = '';
            comments.forEach(comment => {
                const isLiked = likedCommentIds.has(comment.id);
                const isReply = !!comment.parentId;
                // 给一级/二级评论添加不同的类名，便于事件区分
                const commentLevelClass = isChildList ? 'child-comment-item' : 'parent-comment-item';

                html += `
            <div class="comment-item ${commentLevelClass}" id="comment_${comment.id}" data-comment-id="${comment.id}">
                <div class="comment-avatar">
                  <img
                    src="${comment.user?.icon || '../static/images/default-avatar.jpg'}"
                    alt="用户头像"
                    class="w-full h-full rounded-full object-cover"
                  >
                </div>
                <div class="comment-body">
                    <div class="comment-author">${comment.user?.username || '匿名用户'}</div>
                    <div class="comment-time">${formatTime(comment.createdAt)}</div>
                    <div class="comment-content">
                        ${comment.content || '无内容'}
                    </div>
                    <div class="comment-actions">
                        <!-- 点赞按钮添加唯一层级类名：parent-like-btn/child-like-btn -->
                <div class="flex items-center gap-0.5 text-gray-500 hover:text-primary transition-colors comment-action like ${isLiked ? 'liked' : ''} ${isChildList ? 'child-like-btn' : 'parent-like-btn'}">
                <i class="fa ${isLiked ? 'fa-heart text-purple' : 'fa-heart-o'}"></i>
                <span>${comment.likeCount || 0}</span>
                </div>
                    ${!isReply ? `
                        <div class="comment-action reply" data-is-child="false">
                            <i class="fa fa-reply"></i> 回复
                        </div>
                        <div class="comment-action view-replies">
                            <i class="fa fa-comment-dots"></i> 查看回复
                        </div>
                    ` : `
                        <div class="comment-action reply" data-is-child="true">
                            <i class="fa fa-reply"></i> 回复
                        </div>
                    `}
                </div>
                ${!isReply && !isChildList ? `
                        <div class="comment-second-level" id="childComments-${comment.id}" style="display: none;">
                            <div class="text-center py-2 text-gray-500 text-xs">
                                加载回复中...
                            </div>
                        </div>
                    ` : ''}
                </div>
                </div>
                `;
            });
            return html;
        }

        // 时间格式化
        function formatTime(timeStr) {
            if (!timeStr) return '未知时间';
            return timeStr.replace('T', ' ').substring(0, 16);
        }

        // 图片预览
        function handleImagePreview() {
            const imgSrc = $(this).find('img').attr('src');
            $('#modalImage').attr('src', imgSrc); // 设置大图地址
            $('#imagePreviewModal').removeClass('hidden'); // 显示模态框
        }

        // 关闭模态框
        $('#closeModal').on('click', function() {
            $('#imagePreviewModal').addClass('hidden');
        });

        // 点击模态框背景也关闭
        // $('#imagePreviewModal').on('click', function(e) {
        //     if (e.target === this) {
        //         $(this).addClass('hidden');
        //     }
        // });

        // 切换评论区显示/隐藏
        function toggleComments(momentId) {
            const commentsSection = $(`#commentsSection-${momentId}`);
            if (!commentsSection.length) return;

            if (commentsSection.is(':hidden')) {
                commentsSection.show();
                // 加载评论
                getUserLikedComments(momentId).then(() => {
                    getCommentsByMomentId(momentId);
                });
            } else {
                commentsSection.hide();
            }
        }

        // 获取评论列表
        function getCommentsByMomentId(momentId) {
            const commentsListElem = $(`#commentsList-${momentId}`);
            commentsListElem.html(`<div class="text-center py-3 text-gray-500 text-sm">加载评论中...</div>`);

            $.ajax({
                url: "/Moments/getCommentsByCheckinId",
                type: "post",
                dataType: "json",
                data: { checkinId: momentId },
                success: function(res) {
                    const comments = res.data || [];
                    // 新增isChildList参数，标记为一级评论
                    commentsListElem.html(renderCommentList(comments, momentId, false));
                },
                error: function() {
                    commentsListElem.html(`<div class="text-center py-3 text-red-500 text-sm">评论加载失败，请重试</div>`);
                }
            });
        }

        // 获取子评论
        function getChildComments(momentId, parentId) {
            const childContainer = $(`#childComments-${parentId}`);
            if (!childContainer.length) return;

            childContainer.html(`<div class="text-center py-2 text-gray-500 text-xs">加载回复中...</div>`);

            $.ajax({
                url: "/Moments/getChildrenCommentsByParentId",
                type: "post",
                dataType: "json",
                data: { parentId: parentId },
                success: function(res) {
                    const childComments = res.data || [];
                    // 新增isChildList参数，标记为二级子评论
                    childContainer.html(renderCommentList(childComments, momentId, true));
                },
                error: function() {
                    childContainer.html(`<div class="text-center py-2 text-red-500 text-xs">回复加载失败，请重试</div>`);
                }
            });
        }

        // 切换子评论显示/隐藏
        function toggleChildComments(momentId, parentId) {
            const childContainer = $(`#childComments-${parentId}`);
            if (!childContainer.length) return;

            if (childContainer.is(':hidden')) {
                childContainer.show();
                getChildComments(momentId, parentId);
            } else {
                childContainer.hide();
            }
        }

        // 提交评论
        function submitComment(momentId) {
            const inputElem = $(`#commentInput-${momentId}`);
            const commentContent = inputElem.val().trim();
            const commentsListElem = $(`#commentsList-${momentId}`);

            if (!commentContent) {
                alert('请输入评论内容');
                return;
            }

            // 判断是否是回复
            let isReply = false;
            let parentId = null;
            let targetUserName = '';

            if (commentContent.startsWith('@')) {
                isReply = true;
                parentId = inputElem.data('reply-to');
                targetUserName = inputElem.data('target-user');
                if (!parentId) {
                    isReply = false;
                }
            }

            // 临时显示评论
            const tempComment = {
                id: Date.now(),
                user: { username: userName },
                content: commentContent,
                createdAt: new Date().toISOString(),
                likes: 0,
                parentId: parentId,
                parentUser: isReply ? { username: targetUserName } : null
            };

            const currentHtml = commentsListElem.html();
            if (currentHtml.includes('暂无评论') || currentHtml.includes('加载中...')) {
                commentsListElem.html(renderCommentList([tempComment], momentId));
            } else {
                commentsListElem.append(renderCommentList([tempComment], momentId));
            }

            // 清空输入框
            inputElem.val('');
            inputElem.removeData('reply-to');
            inputElem.removeData('target-user');

            // 提交到服务器
            const url = isReply ? "/Moments/replyComment" : "/Moments/addComment";
            $.ajax({
                url: url,
                type: "post",
                dataType: "json",
                data: {
                    checkinId: momentId,
                    userId: userId,
                    content: commentContent,
                    parentId: isReply ? parentId : null
                },
                success: function(res) {
                    // 重新加载评论列表
                    getCommentsByMomentId(momentId);
                    // 更新评论数
                    if (res.data) {
                        updateMomentReviewCount(momentId, res.data);
                    }
                },
                error: function() {
                    // 失败时移除临时评论
                    $(`#comment_${tempComment.id}`).remove();
                    alert('评论提交失败，请重试');
                }
            });
        }

        // 回复评论
        function replyToComment(momentId, commentId, targetUserName, isChild = false) {
            const inputElem = $(`#commentInput-${momentId}`);
            const commentsSection = $(`#commentsSection-${momentId}`);

            if (!inputElem.length || !commentsSection.length) return;

            // 确保评论区可见
            if (commentsSection.is(':hidden')) {
                commentsSection.show();
                getCommentsByMomentId(momentId);
            }

            // 区分场景：如果是回复子评论，只填充子评论的作者名；否则填充主评论的作者名
            let replyPrefix = `@${targetUserName} `;
            inputElem.val(replyPrefix);
            inputElem.data('reply-to', commentId);
            inputElem.data('target-user', targetUserName);
            inputElem.focus();
            inputElem[0].selectionStart = inputElem[0].selectionEnd = inputElem.val().length;
        }

        // 切换动态点赞状态
        function toggleMomentLike(momentId) {
            const isLiked = likedMomentIds.has(momentId);
            const likeBtn = $(`#moment_${momentId} .like-btn`);
            const likeIcon = likeBtn.find('i');
            const likeCountElem = likeBtn.find('span');
            const currentCount = parseInt(likeCountElem.text().match(/\d+/)[0]) || 0;

            // 临时更新UI
            if (isLiked) {
                likeBtn.removeClass('liked');
                likeIcon.removeClass('fa-heart text-purple').addClass('fa-heart-o');
                likeCountElem.text(`点赞 (${currentCount - 1})`);
                likedMomentIds.delete(momentId);
            } else {
                likeBtn.addClass('liked');
                likeIcon.removeClass('fa-heart-o').addClass('fa-heart text-purple');
                likeCountElem.text(`点赞 (${currentCount + 1})`);
                likedMomentIds.add(momentId);
            }

            // 调用接口
            const url = isLiked ? "/checkings/cancelCheckinLike" : "/checkings/likeCheckin";
            $.ajax({
                url: url,
                type: "post",
                dataType: "json",
                data: {
                    checkinId: momentId,
                    userId: userId
                },
                success: function(res) {
                    console.log("点赞：",res)
                    if (res.data?.newLikeCount !== undefined) {
                        likeCountElem.text(`点赞 (${res.data.newLikeCount})`);
                    }
                },
                error: function() {
                    // 失败时恢复状态
                    if (isLiked) {
                        likeBtn.addClass('liked');
                        likeIcon.removeClass('fa-heart-o').addClass('fa-heart text-purple');
                        likeCountElem.text(`点赞 (${currentCount})`);
                        likedMomentIds.add(momentId);
                    } else {
                        likeBtn.removeClass('liked');
                        likeIcon.removeClass('fa-heart text-purple').addClass('fa-heart-o');
                        likeCountElem.text(`点赞 (${currentCount})`);
                        likedMomentIds.delete(momentId);
                    }
                    alert('操作失败，请重试');
                }
            });
        }

        // 切换评论点赞状态
        function toggleCommentLike(momentId, commentId) {
            // 精准定位当前评论元素（通过ID直接选择，避免closest匹配错误）
            const commentElem = $(`#comment_${commentId}`);
            if (!commentElem.length) return; // 若元素不存在，直接返回，避免报错

            const isLiked = likedCommentIds.has(commentId);
            const likeBtn = commentElem.find('.comment-action.like');
            const likeIcon = likeBtn.find('i');
            const likeCountElem = likeBtn.find('span');
            const currentCount = parseInt(likeCountElem.text().trim()) || 0;

            // 临时更新UI（与动态点赞样式对齐）
            if (isLiked) {
                likeBtn.removeClass('liked');
                likeIcon.removeClass('fa-heart text-purple').addClass('fa-heart-o');
                likeCountElem.text(currentCount - 1);
                likedCommentIds.delete(commentId);
            } else {
                likeBtn.addClass('liked');
                likeIcon.removeClass('fa-heart-o').addClass('fa-heart text-purple');
                likeCountElem.text(currentCount + 1);
                likedCommentIds.add(commentId);
            }

            // 调用接口（保持原逻辑）
            const url = isLiked ? "/checkings/cancelCommentLike" : "/checkings/likeComment";
            $.ajax({
                url: url,
                type: "post",
                dataType: "json",
                data: {
                    commentId: commentId,
                    userId: userId
                },
                success: function(res) {
                    console.log("点赞成功：", res);
                    if (res.data !== undefined) {
                        likeCountElem.text(res.data);
                    }
                },
                error: function() {
                    // 失败时恢复状态
                    if (isLiked) {
                        likeBtn.addClass('liked');
                        likeIcon.removeClass('fa-heart-o').addClass('fa-heart text-purple');
                        likeCountElem.text(currentCount);
                        likedCommentIds.add(commentId);
                    } else {
                        likeBtn.removeClass('liked');
                        likeIcon.removeClass('fa-heart text-purple').addClass('fa-heart-o');
                        likeCountElem.text(currentCount);
                        likedCommentIds.delete(commentId);
                    }
                    alert('操作失败，请重试');
                }
            });
        }

        // 更新动态的评论数
        function updateMomentReviewCount(momentId, newCount) {
            const commentBtn = $(`#moment_${momentId} .comment-btn span`);
            const commentTitle = $(`#commentsSection-${momentId} .comments-title`);

            if (commentBtn.length) {
                commentBtn.text(`评论 (${newCount})`);
            }
            if (commentTitle.length) {
                commentTitle.text(`评论 (${newCount})`);
            }
        }

        // 获取用户已点赞的动态ID
        function getUserLikedMoments() {
            $.ajax({
                url: "/checkings/getUserLikedCheckins",
                type: "post",
                dataType: "json",
                data: { userId: userId },
                success: function(res) {
                    console.log("已点赞的打卡：", res)
                    if (res.data) {
                        likedMomentIds = new Set(res.data);
                        // 重新渲染已加载的动态以更新点赞状态
                        $('.moment-item').each(function() {
                            const momentId = parseInt($(this).attr('id').replace('moment_', ''));
                            const likeBtn = $(this).find('.like-btn');
                            const likeIcon = likeBtn.find('i');

                            if (likedMomentIds.has(momentId)) {
                                likeBtn.addClass('liked');
                                likeIcon.removeClass('fa-heart-o').addClass('fa-heart text-purple');
                            } else {
                                likeBtn.removeClass('liked');
                                likeIcon.removeClass('fa-heart text-purple').addClass('fa-heart-o');
                            }
                        });
                    }
                }
            });
        }

        // 获取用户已点赞的评论ID
        function getUserLikedComments(momentId) {
            return new Promise((resolve) => {
                $.ajax({
                    url: "/checkings/getUserLikedComments",
                    type: "post",
                    dataType: "json",
                    data: {
                        userId: userId,
                        checkinId: momentId
                    },
                    success: function(res) {
                        console.log("已点赞的评论：",res)
                        if (res.data) {
                            likedCommentIds = new Set(res.data);
                        }
                        resolve();
                    },
                    error: function() {
                        resolve();
                    }
                });
            });
        }

        // 获取用户ID
        function getUserIdByName(username, callback) {
            $.ajax({
                url: "/checkings/getUserIdByName",
                type: "post",
                dataType: "json",
                data: { userName: username },
                success: function(res) {
                    if (res.data && callback) callback(res.data);
                },
                error: function() {
                    console.log("获取用户ID失败");
                }
            });
        }

        // 获取用户头像
        function showUserInfoByUserId(id) {
            $.ajax({
                url: "/Moments/showUserInfoByUserId",
                type: "post",
                dataType: "json",
                data: { userId: id },
                success: function(res) {
                    if (res.data?.icon) {
                        $('#userAvatar').html(`<img src="${res.data.icon}" class="w-full h-full rounded-full object-cover">`);
                        $('#userAvatar').removeClass('bg-gradient-to-r from-purple-400 to-pink-500');
                    }
                }
            });
        }
    });
</script>
</body>
</html>